package com.travelms.service.commonuserpage.publicchat;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    String name;

    public Client(String name) throws IOException {
        this.name = name;
        //创建连接

        Socket socket = new Socket("127.0.0.1", 15000);
        System.out.println("-----欢迎来到公共聊天室，请文明发言哦QaQ-----");
        //写一个线程来接受数据
        new Thread(new ClientRunnable(socket)).start();

        //往服务器传数据
        talkToServe(socket);
    }

    private void talkToServe(Socket socket) throws IOException {
        Scanner sc = new Scanner(System.in);
        //获取输出流
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        //写出数据
        System.out.println("     可以开始说话了，输入exit退出");
        while (true) {

            String s = sc.nextLine();
            bufferedWriter.write(name + "-" + s);
            bufferedWriter.newLine();
            bufferedWriter.flush();
            if("exit".equals(s)){
                break;
            }
        }

        socket.close();


    }
}

class ClientRunnable implements Runnable{
    Socket socket;
    public ClientRunnable(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        //接受数据
        try {
            while (true){
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                System.out.println(bufferedReader.readLine());

            }
        } catch (IOException e) {

        }

    }
}